package ywpt.core.web;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsStatics;


import ywpt.components.acegi.domain.Operation;
import ywpt.components.acegi.domain.Role;
import ywpt.components.acegi.domain.User;
import ywpt.service.system.UserService;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 
 * BaseAction 2007-5-7 上午12:33:00
 * 
 * @author <a href="mailto:mrwyxster@gmail.com">Oliver Wen</a>
 * 
 */
public abstract class BaseAction extends ActionSupport {
	
	public UserService userService;	
	
	public UserService getUserService()
	{
		return userService;
	}

	public void setUserService(UserService userService)
	{
		this.userService=userService;
	}

	protected String getIPAddress() {
		return ServletActionContext.getRequest().getRemoteAddr();
	}

	protected HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	protected HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	protected String getCurrentUserNameOld() {
/*		Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Subject currentUser = SecurityUtils.getSubject();  
		String username = null;
		if (obj instanceof UserDetails) {
			username = ((UserDetails) obj).getUsername();
		} else {
			username = obj.toString();
		}*/
		System.out.println("can reach getCurrentUserName");

		String username = null;
		User user = null;

		HttpSession session = getRequest().getSession(false); 
	     
		if (null != session) {
	    	  System.out.println("getCurrentUserName session is not null + id = "+ session.getId() );
	          user = (User)session.getAttribute( "USER_SESSION" );
	          if (null!=user) {
	        	  System.out.println("getCurrentUserName user is not null" );
	              username = (String)user.getUsername();
	              if (null!=username) {
	            	  
		              System.out.println("getCurrentUserName has user:"+user.getUsername());
		              return username;
	              } else
	            	  System.out.println("username is null");
	            	  
	          } else
	        	  System.out.println("getCurrentUserName user is  null" );
	     } else
	    	 System.out.println("getCurrentUserName session is  null" );

		return null;
	}

	protected String getCurrentUserName() {
		String username = null;
		User user = null;
		HttpServletRequest request= getRequest();
		if (null != request) {
			Cookie cookies[]=request.getCookies();
			Cookie sCookie=null; 
			String svalue=null; 
			String sname=null; 
			for(int i=0;i<cookies.length-1;i++) {//用一个循环语句遍历刚才建立的Cookie对象数组 
				sCookie=cookies[i];					 //取出数组中的一个Cookie对象 
				sname=sCookie.getName(); 			//取得这个Cookie的名字 
				if (sname.equals("username")) {
					svalue=sCookie.getValue(); //取得这个Cookie的内容 
				}
			}
			if ( svalue != null ) {
				/*System.out.println("getCurrentUserName has  user Name:  "+ svalue );*/
				return svalue;
			} else
	        	  /*System.out.println("getCurrentUserNameFromCookie UserName is  null" );*/
				return null;
	     } else
	    	 /*System.out.println("getCurrentUserNameFromCookie request is  null" );*/
	    	
		 return null;
	}

	
	
	protected String getCurrentFullName()
	{
		String fullName = "";
		if(this.getCurrentUser()!=null)
			fullName=this.getCurrentUser().getFullName();
		return fullName;
	}
	
	protected User getCurrentUser() {
/*		Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if (obj instanceof UserDetails) {
			return (User) obj;
		}*/
		System.out.println("can reach getCurrentUser");
		String username = null;
		User user = null;
		user = getCurrentUserFromCookie();
		if (null != user) {
			System.out.println("getCurrentUser user is not null + username = "+ user.getUsername() );
	        return user;
	     } else
	    	System.out.println("getCurrentUser user is null" );
		 return null;
	}
	
	
	protected User getCurrentUserFromCookie() {
		/*
		 * Object obj =
		 * SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		 * if (obj instanceof UserDetails) { return (User) obj; }
		 */
		System.out.println("can reach getCurrentUserFromCookie");
		String username = null;
		User user = null;
		username = getCurrentUserName();
		if (null == userService)
			System.out.println("userService == null");
		
		if (null != username) {
			System.out
					.println("getCurrentUserFromCookie user is not null + username = "
							+ username);
			user = userService.getUserByUsername(username);
			if (null != user) {
				System.out.println("getCurrentUserFromCookie user is not null");
				return user;
			} else
				System.out.println("getCurrentUserFromCookie user is  null");
		} else
			System.out.println("getCurrentUserFromCookie username is  null");
		return null;
	}	
	
	protected List<Operation> getOperationByCurrentUser(User user)
	{
		List<Operation> operation=new ArrayList<Operation>();
		Iterator<Role> roles=user.getRoles().iterator();
		while(roles.hasNext())
		{
			Role role=roles.next();
			operation.addAll(role.getOperations());
			Iterator<Operation> iterator=role.getOperations().iterator();
			while(iterator.hasNext())
			{
				operation.add(iterator.next());
			}
		}
		return operation;
	}
	
	protected HashMap<String,Operation> getOperMapByUser(User user)
	{
		HashMap<String,Operation> operation=new HashMap<String,Operation>();/*
		System.out.println(userService);
		User newUser=user;
		if(userService!=null)
		{
			newUser= userService.getUserById(user.getId());		
		}*/
		User newUser= userService.getUserById(user.getId());	
		Iterator<Role> roles=newUser.getRoles().iterator();
		while(roles.hasNext())
		{
			Role role=roles.next();
			Iterator<Operation> iterator=role.getOperations().iterator();
			while(iterator.hasNext())
			{
				Operation temp=iterator.next();
				operation.put(temp.getOperationCode().toString(),temp);
			}
		}
		return operation;
	}
	protected HashMap<String,Operation> getOperMapByRoles(Set<Role> roless)
	{
		HashMap<String,Operation> operation=new HashMap<String,Operation>();
		/*
		System.out.println(userService);
		User newUser=user;
		if(userService!=null)
		{
			newUser= userService.getUserById(user.getId());		
		}*/
		Iterator<Role> roles = roless.iterator();
		while(roles.hasNext())
		{
			Role role=roles.next();
			Iterator<Operation> iterator=role.getOperations().iterator();
			while(iterator.hasNext())
			{
				Operation temp=iterator.next();
				operation.put(temp.getOperationCode().toString(),temp);
			}
		}
		return operation;
	}
	
	protected String getPublishType() throws Exception {
		try {
			String ACTIONPATH = "WEB-INF/propertis/actions.properties";
			// 属性文件
			Properties prop = new Properties();
			// 获取servlet上下文的绝对路径，如：C:\Program Files\Apache\Tomcat
			// 6.0\webapps\fee\

			String path = ServletActionContext.getServletContext().getRealPath(
					"\\");
			// 把文件读入文件输入流，存入内存中
			FileInputStream fis = new FileInputStream(new File(path
					+ ACTIONPATH));
			// 加载文件流的属性
			prop.load(fis);
			String app_publish_type = prop.getProperty("app_publish_type");
			return app_publish_type;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
